package com.lixw.langchain.config;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName: RedisChatMemoryStore
 * @Description:
 * @Author: xuweiLi
 * @Create: 2025/8/24 13:52
 **/
@Slf4j
@Component
public class RedisChatMemoryStore implements ChatMemoryStore {

    public static final String CHAT_MEMORY_PREFIX = "CHAT_MEMORY:";

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        log.info("Getting messages from Redis 获取所有记忆，记忆id:{{}}", memoryId);
        String dbVal = redisTemplate.opsForValue().get(CHAT_MEMORY_PREFIX + memoryId);
        log.info("获取所有记忆结果：{}", dbVal);
        return ChatMessageDeserializer.messagesFromJson(dbVal);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        log.info("Updating messages from Redis id:{{}},更新内容:{}", memoryId, messages);
        redisTemplate.opsForValue()
                .set(CHAT_MEMORY_PREFIX + memoryId, ChatMessageSerializer.messagesToJson(messages));
    }

    @Override
    public void deleteMessages(Object memoryId) {
        log.warn("删除会话执行");
        log.info("Deleting messages from Redis id:{{}}", CHAT_MEMORY_PREFIX + memoryId);
    }
}